package com.bocloud.cmp.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.bocloud.cmp.dao.SafetyDeviceDao;
import com.bocloud.cmp.entity.resource.SafetyDevice;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.intf.impl.JdbcGenericDao;
import com.bocloud.database.utils.SQLHelper;

/**
 * 安全设备抽象DAO接口实现类
 * 
 * @author wei wei
 * @version 1.0
 * @since 2017.02.23
 */
@Repository("safetyDeviceDao")
public class SafetyDeviceDaoImpl extends JdbcGenericDao<SafetyDevice, Long> implements SafetyDeviceDao {

	@Override
	public SafetyDevice query(Long id) throws Exception {
		String sql = "select a.*,b.name rackname from safety_device a left join rack b on a.rack_id = b.id where a.is_deleted = 0 and a.id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		List<SafetyDevice> list = this.list(SafetyDevice.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public List<SafetyDevice> list(int page, int rows, List<Param> params, Map<String, String> sorter)
			throws Exception {
		String sql = "select a.*,b.name rackname,c.name roomname from safety_device a left join rack b on a.rack_id = b.id left join room c on b.room_id = c.id where a.is_deleted = 0";
		sql = SQLHelper.buildRawSql(sql, page, rows, params, sorter, "a");
		Map<String, Object> paramMap = SQLHelper.getParam(params);
		return this.list(SafetyDevice.class, sql, paramMap);
	}

	@Override
	public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select a.id,a.name from safety_device a where a.is_deleted = 0";
		sql = SQLHelper.buildSql(sql, 1, Integer.MAX_VALUE, params, sorter, "a");
		Map<String, Object> paramMap = SQLHelper.getParam(params);
		List<SafetyDevice> devices = this.list(SafetyDevice.class, sql, paramMap);
		List<SimpleBean> beans = new ArrayList<SimpleBean>();
		for (SafetyDevice device : devices) {
			beans.add(new SimpleBean(device.getId(), device.getName()));
		}
		return beans;
	}

	@Override
	public int count(List<Param> params) throws Exception {
		String sql = "select count(1) from safety_device a where a.is_deleted = 0";
		sql = SQLHelper.buildRawSql(sql, params, null, "a");
		Map<String, Object> paramMap = SQLHelper.getParam(params);
		return this.countQuery(sql, paramMap).intValue();
	}

	@Override
	public boolean remove(Long id, Long userId) throws Exception {
		String sql = "update safety_device set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;
	}

}
